package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"server/http/form"
	"server/repository/model"
	"server/service"
)

func Reg(c *gin.Context) {
	queryForm := form.RegForm{}
	if err := c.ShouldBindWith(&queryForm, binding.JSON); err != nil {
		ResultError(c, form.GetErrorMsg(queryForm, err))
		return
	}

	var m = service.UserRegisterOpt{
		Name: queryForm.Name,
		Pwd:  queryForm.Pwd,
	}

	userModel, err := service.Us.Register(c.Request.Context(), &m)
	if err != nil {
		ResultError(c, err)
		return
	}

	ResultSuccess(c, map[string]any{
		"name":  userModel.Name,
		"token": userModel.Token,
		"uuid":  userModel.Uuid,
	})
}

func Login(c *gin.Context) {
	queryForm := form.LoginForm{}
	if err := c.ShouldBindWith(&queryForm, binding.JSON); err != nil {
		ResultError(c, form.GetErrorMsg(queryForm, err))
		return
	}

	userModel, err := service.Us.Login(c.Request.Context(), queryForm.Name, queryForm.Pwd)
	if err != nil {
		ResultError(c, err)
		return
	}

	ResultSuccess(c, map[string]any{
		"name":  userModel.Name,
		"token": userModel.Token,
		"uuid":  userModel.Uuid,
	})
}

func ChangePwd(c *gin.Context) {
	queryForm := form.ChangePwdForm{}
	if err := c.ShouldBindWith(&queryForm, binding.JSON); err != nil {
		ResultError(c, form.GetErrorMsg(queryForm, err))
		return
	}

	user, _ := c.Get("user")
	userModel := user.(model.UserModel)

	err := service.Us.ChangePwd(c.Request.Context(), &service.ChangePwdOpt{
		User:   &userModel,
		OldPwd: queryForm.OldPwd,
		NewPwd: queryForm.NewPwd,
	})
	if err != nil {
		ResultError(c, err)
		return
	}

	ResultSuccess(c, nil)

}
